﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Consul;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace X22.Consul.Extension
{
    public class ConsulServiceDiscovery : IConsulServiceDiscovery
    {
        private readonly string _consulAddress;
        private string _serviceName;
        private readonly string _serviceHead;
        private readonly Dispatcher _dispatcher;

        public ConsulServiceDiscovery(IOptions<ServiceDiscoveryOption> options)
        {
            _consulAddress = options.Value.ConsulAddress;
            _serviceName = options.Value.ServiceName;
            _serviceHead = options.Value.ServiceHead;
            _dispatcher = options.Value.Dispatcher;
        }
        public Task<string> ConsulUrl()
        {
            using (var consulClient = new ConsulClient(a => a.Address = new Uri(_consulAddress)))
            {
                var serviceList = consulClient.Catalog.Service(_serviceName).Result.Response;
                if (serviceList != null && serviceList.Any())
                {
                    CatalogService myService = null;

                    #region  加策略
                    myService = serviceList.ElementAt(new Random().Next(serviceList.Length));
                    switch (_dispatcher)
                    {
                        case Dispatcher.AverageDispatcher:
                            break;
                        default:
                            break;
                    }
                    #endregion

                    var result = $"{_serviceHead}://{myService.ServiceAddress}:{myService.ServicePort}";
                    return Task.FromResult(result);
                }
            }

            throw new Exception("请求地址错误");
        }
    }
}
